//
//  GameAventureViewController.m
//  ToucheTouche
//
//  Created by Jordan Montel on 10/01/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "GameAventureViewController.h"
#import "Level.h"

@implementation GameAventureViewController
@synthesize labelLevel;

@synthesize buttonPause;
@synthesize button11,button12,button13,button14,button15,button16,button17,button18
,button21,button22,button23,button24,button25,button26,button27,button28,button31,button32,button33,button34,button35,button36,button37,button38,button41,button42,button43,button44,button45,button46,button47,button48;
@synthesize allButtons;
@synthesize imageView11, imageView12,imageView13,imageView14,imageView15,imageView16,imageView17,imageView18,imageView21,imageView22,imageView23,imageView24,imageView25,imageView26,imageView27,imageView28,imageView31,imageView32,imageView33,imageView34,imageView35,imageView36,imageView37,imageView38,imageView41,imageView42,imageView43,imageView44,imageView45,imageView46,imageView47,imageView48;
@synthesize allImagesView;
@synthesize progressViewLife;
@synthesize labelLife, labelScore, labelTime;
@synthesize floatScoreToAddByLevel, floatScoreLastLevel;
@synthesize intRandom, intLastRandom, intLastLevel;
@synthesize boolEndGame;
@synthesize alertViewExtraLevel, alertViewNewLevel;
@synthesize fileNameImage;

/* Methode pour aller a la vue pause */
- (IBAction)pushPause {
    [self stopTimer];
    [self stopTimerLevel];
    
    pauseViewController = [[PauseViewController alloc] initWithNibName:@"PauseViewController" bundle:nil];
    pauseViewController.delegate = self;
    
    // pousser la vue pause
    pauseViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:pauseViewController animated:YES];
    [pauseViewController release];
}

/* methode action ajout de points et suppression de vies */
- (IBAction)actionImage:(id)sender {
    boolImageNotTouched = NO;
    [self removeLife:sender]; //appel methode suppression de vies
    [self addScore:sender]; //appel methode ajout de points
}

/* methode qui affiche l'image au hasard sur la grille */
- (void)randomPositionImage {
    // boucle pour effacer l'ancienne image
    for (UIImageView *imageView in allImagesView) {
        imageView.image = nil;
    }
    intRandom = (arc4random() % 32);
    while (intRandom == intLastRandom) {
        intRandom = (arc4random() % 32);
    }

    UIImageView *img = [allImagesView objectAtIndex:intRandom];
    img.image = [UIImage imageNamed:[[Level sharedLevel] fileImageName]];
    intLastRandom = intRandom;
    [[[Level sharedLevel] fileImageName] release];


    
    [self imageNotTouched];
}

/* methode pour enlever de la vie quand l'image n'est pas touchee */
- (void)imageNotTouched {
    if (boolImageNotTouched) {
        if ([[Level sharedLevel] floatLife] <= 5) {
            [self endGame];
        }
        else {
            [[Level sharedLevel] removeLife:[[Level sharedLevel] floatLifeToRemove] :[[Level sharedLevel] floatLifeProgressToRemove]];
            labelLife.text = [NSString stringWithFormat:@"%.0f", [[Level sharedLevel] floatLife]];
            progressViewLife.progress = [[Level sharedLevel] floatLifeProgress];
        }
    }
}

/* methode timer apparition image */
- (void)timerImage {
    timerMouvement = [[NSTimer scheduledTimerWithTimeInterval:[[Level sharedLevel] timeImage] target:self selector:@selector(randomPositionImage) userInfo:nil repeats:YES] retain];
}

/* methode timer niveau */
- (void)timerLevel:(int)intTimeLvl {
    timerLevel = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(currentLevel) userInfo:nil repeats:YES] retain];
    // Afficher le compteur
    labelTime.text = [NSString stringWithFormat:@"%ds", [[Level sharedLevel] intTimeLevel]];
}

/* methode pour relancer le timer du niveau apres la pause */
- (void)timerLevelBackToGame {
    [[Level sharedLevel] setIntTimeLevel:[[Level sharedLevel] intTimeLevel]];
    [self timerLevel:[[Level sharedLevel] intTimeLevel]];
}

/* methode pour decroitre le temps */
- (void)currentLevel {  
    [[Level sharedLevel] removeTimeLevel:1];
    labelTime.text = [NSString stringWithFormat:@"%ds", [[Level sharedLevel] intTimeLevel]];
    
    NSInteger intTimeLvl = [[Level sharedLevel] intTimeLevel];

    // Arrète le NSTimer lorsque le compte à rebour est à zéro
    if (intTimeLvl == 0 && floatScoreLastLevel < [[Level sharedLevel] floatScoreForExtra]) {
        [self stopTimerLevel];
        [self stopTimer];
        
        NSString *comment;
        
        if ([[Level sharedLevel] intCurrentLevel] == 1) {
            comment = @"L'apparition des images va accélérer";
        }
        else if ([[Level sharedLevel] intCurrentLevel] == 2) {
            comment = @"L'apparition des images va accélérer\nl'image pourra être remplacée par une image piège qui fera perdre de la vie et des points";
        }
        else if ([[Level sharedLevel] intCurrentLevel] == 3) {
            comment = @"L'apparition des images va accélérer\nl'image pourra être remplacée par une image piège qui fera perdre de la vie et des points";
        }
        else if ([[Level sharedLevel] intCurrentLevel] == 4) {
            comment = @"L'apparition des images va accélérer\nl'image pourra être remplacée par une image piège qui fera perdre de la vie et des points\nl'image pourra être remplacée par une image bombe qui fera perdre de la vie et des points\nl'image pourra être remplacée par une image boost qui fera gagner des points";
        }
        else if ([[Level sharedLevel] intCurrentLevel] == 5) {
            comment = @"L'apparition des images va accélérer\nUne seconde image de jeu va apparaître en plus de la première\nl'image pourra être remplacée par une image piège qui fera perdre de la vie et des points\nl'image pourra être remplacée par une image bombe qui fera perdre de la vie et des points\nl'image pourra être remplacée par une image boost qui fera gagner des points";
        }
        
        alertViewNewLevel = [[UIAlertView alloc] initWithTitle:@"Nouveau niveau !" message:[NSString stringWithFormat:@"Passage au niveau : %d\nScore actuel : %.0f\nVie actuelle : %.0f/100\n\n%@", [[Level sharedLevel] intCurrentLevel]+1, [[Level sharedLevel] floatScore], [[Level sharedLevel] floatLife], comment] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertViewNewLevel show];
        [alertViewNewLevel release];
    }
    else if (intTimeLvl == 0 && floatScoreLastLevel >= [[Level sharedLevel] floatScoreForExtra]) {
        [self stopTimerLevel];
        [self stopTimer];
        
        NSString *comment;
        
        if ([[Level sharedLevel] intCurrentLevel] == 1) {
            comment = @"Il faut toucher le plus d'images possible";
        }
        else if ([[Level sharedLevel] intCurrentLevel] == 2) {
            comment = @"5 images vont apparaître à plusieurs reprises, il faut toucher l'image unique pour gagner des points";
        }
        else if ([[Level sharedLevel] intCurrentLevel] == 3) {
            comment = @"Au milieu de l’écran se trouve une image, dès qu'elle change il faut toucher la nouvelle image le plus rapidement possible";
        }
        else if ([[Level sharedLevel] intCurrentLevel] == 4) {
            comment = @"Au milieu de l’écran se trouve une image, il faut la toucher le plus de fois possible";
        }
        else if ([[Level sharedLevel] intCurrentLevel] == 5) {
            comment = @"au milieu de l’écran se trouvent 5 images noires, toutes les 0,5 seconde une image s’allume en rouge, il faut essayer de la toucher avant qu’elle disparaisse";
        }
        
        alertViewExtraLevel = [[UIAlertView alloc] initWithTitle:@"Extra Débloqué !" message:[NSString stringWithFormat:@"Extra du Niveau : %d\nScore actuel : %.0f\nVie : %.0f/100\n%@ !", [[Level sharedLevel] intCurrentLevel], [[Level sharedLevel] floatScore], [[Level sharedLevel] floatLife], comment] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertViewExtraLevel show];
        [alertViewExtraLevel release];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView == alertViewExtraLevel) {
        if (buttonIndex == 0) {
            [self pushExtraView];
        }
    }
    if (alertView == alertViewNewLevel) {
        if (buttonIndex == 0) {
            NSLog(@"changement de niveau");
                        
            // mise a jour du nouveau niveau [bonnes valeurs]
            // init : score, score to add, score for extra, life, life to remove, lifeprogress, lifeprogress to remove, time level, time level to remove, current level, time image, background, image
            
            if ([[Level sharedLevel] intCurrentLevel] == 1) {
                [[Level sharedLevel] initLevel:[[Level sharedLevel] floatScore] :10 :250 :[[Level sharedLevel] floatLife] :5 :[[Level sharedLevel] floatLifeProgress] :0.05 :31 :1 :2 :0.8: @"": @"imageTest.png"];
            }
            else if ([[Level sharedLevel] intCurrentLevel] == 2) {
                [[Level sharedLevel] initLevel:[[Level sharedLevel] floatScore] :15 :750 :[[Level sharedLevel] floatLife] :5 :[[Level sharedLevel] floatLifeProgress] :0.05 :36 :1 :3 :0.7: @"": @"imageTest.png"];
            }
            else if ([[Level sharedLevel] intCurrentLevel] == 3) {
                [[Level sharedLevel] initLevel:[[Level sharedLevel] floatScore] :20 :1100 :[[Level sharedLevel] floatLife] :5 :[[Level sharedLevel] floatLifeProgress] :0.05 :41 :1 :4 :0.6: @"": @"imageTest.png"];
            }
            else if ([[Level sharedLevel] intCurrentLevel] == 4) {
               [[Level sharedLevel] initLevel:[[Level sharedLevel] floatScore] :25 :1500 :[[Level sharedLevel] floatLife] :5 :[[Level sharedLevel] floatLifeProgress] :0.05 :46 :1 :5 :0.6: @"": @"imageTest.png"];
            }
            else if ([[Level sharedLevel] intCurrentLevel] == 5) {
                [[Level sharedLevel] initLevel:[[Level sharedLevel] floatScore] :30 :1500 :[[Level sharedLevel] floatLife] :5 :[[Level sharedLevel] floatLifeProgress] :0.05 :55 :1 :6 :0.5: @"": @"imageTest.png"];
            }
            
            [self initLabel]; // init des labels
            [self timerImage]; // deplacement image
            [self timerLevel:[[Level sharedLevel] intTimeLevel]]; // temps du niveau
            
        }
    }
}

/* methode arret timer */
- (void)stopTimer {
    [timerMouvement invalidate];
    timerMouvement = nil;
}

/* methode arret timer niveau */
- (void)stopTimerLevel {
    [timerLevel invalidate];
    timerLevel = nil;
}

/* methode push extra view */
- (void)pushExtraView {
    
    [self stopTimer];
    [self stopTimerLevel];
    
    if ([[Level sharedLevel] intCurrentLevel] == 1) {
        extra1ViewController = [[Extra1ViewController alloc] initWithNibName:@"Extra1ViewController" bundle:nil];
        extra1ViewController.delegate = self;
        
        extra1ViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self presentModalViewController:extra1ViewController animated:YES];
        [extra1ViewController release];
    }
    else if ([[Level sharedLevel] intCurrentLevel] == 2) {
        extra2ViewController = [[Extra2ViewController alloc] initWithNibName:@"Extra2ViewController" bundle:nil];
        extra2ViewController.delegate = self;
        
        extra2ViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self presentModalViewController:extra2ViewController animated:YES];
        [extra2ViewController release];
    }
    else if ([[Level sharedLevel] intCurrentLevel] == 3) {
        extra3ViewController = [[Extra3ViewController alloc] initWithNibName:@"Extra3ViewController" bundle:nil];
        extra3ViewController.delegate = self;
        
        extra3ViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self presentModalViewController:extra3ViewController animated:YES];
        [extra3ViewController release];
    }
    else if ([[Level sharedLevel] intCurrentLevel] == 4) {
        extra4ViewController = [[Extra4ViewController alloc] initWithNibName:@"Extra4ViewController" bundle:nil];
        extra4ViewController.delegate = self;
        
        extra4ViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self presentModalViewController:extra4ViewController animated:YES];
        [extra4ViewController release];
    }
    else if ([[Level sharedLevel] intCurrentLevel] == 5) {
        extra5ViewController = [[Extra5ViewController alloc] initWithNibName:@"Extra5ViewController" bundle:nil];
        extra5ViewController.delegate = self;
        
        extra5ViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self presentModalViewController:extra5ViewController animated:YES];
        [extra5ViewController release];
    }
}

/* methode ajout de points au score */
- (void)addScore:(id)sender {
    UIButton *button = [allButtons objectAtIndex:intRandom];
    if(button == sender) {
        boolImageNotTouched = NO;
        [[Level sharedLevel] addScore:[[Level sharedLevel] floatScoreToAdd]]; // ajout au score la valeur gagnee quand image touchee
        labelScore.text = [NSString stringWithFormat:@"%.0f", [[Level sharedLevel] floatScore]];
        floatScoreLastLevel = [[Level sharedLevel] floatScore]; // sauvegarde du score du niveau
        [self randomPositionImage];
        [self stopTimer];
        [self timerImage];
        boolImageNotTouched = YES;
    }
}

/* methode ajout de points au score apres l'extra */
- (void)addScoreNextExtra {
    if ([[Level sharedLevel] intCurrentLevel] == 1) {
        [[Level sharedLevel] addScore:[[Level sharedLevel] floatExtraScore]];
    }
    else if ([[Level sharedLevel] intCurrentLevel] == 2) {
        [[Level sharedLevel] addScore:[[Level sharedLevel] floatExtraScore]];
    }
    else if ([[Level sharedLevel] intCurrentLevel] == 3) {
        [[Level sharedLevel] addScore:[[Level sharedLevel] floatExtraScore]];
    }
    else if ([[Level sharedLevel] intCurrentLevel] == 4) {
        [[Level sharedLevel] addScore:[[Level sharedLevel] floatExtraScore]];
    }
    else if ([[Level sharedLevel] intCurrentLevel] == 5) {
        [[Level sharedLevel] addScore:[[Level sharedLevel] floatExtraScore]];
    }
    labelScore.text = [NSString stringWithFormat:@"%.0f", [[Level sharedLevel] floatScore]];
}

/* methode suppression de vies */
- (void)removeLife:(id)sender {
    UIButton *button = [allButtons objectAtIndex:intRandom];
    if ([[Level sharedLevel] floatLife] <= 5) {
        [self endGame];
    }
    else {
        if(button != sender) {
            [[Level sharedLevel] removeLife:[[Level sharedLevel] floatLifeToRemove] :[[Level sharedLevel] floatLifeProgressToRemove]];
            labelLife.text = [NSString stringWithFormat:@"%.0f", [[Level sharedLevel] floatLife]];
            progressViewLife.progress = [[Level sharedLevel] floatLifeProgress];
        } 
    }
}

/* methode d'initialisation des images */
- (void)setCurrentLevelDesign:(NSString *)fileBackground:(NSString *)fileImage {
    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:fileBackground]];
    self.view.backgroundColor = background;
    [background release];
    
    fileImage = [NSString stringWithFormat: @"imageTest2.png"];
    
    
    fileNameImage = fileImage;
}

/* methode restart une nouvelle partie */
- (void)restartGame {
    // mise a jour du nouveau niveau [bonnes valeurs]
    // init : score, score to add, score for extra, life, life to remove, lifeprogress, lifeprogress to remove, time level, time level to remove, current level, time image, background, image
    //[[Level sharedLevel] initLevel:0 :5 :200 :100 :5 :1 :0.05 :31 :1 :1: 1: @"backgroundLevel1.png": @"imageLevel1.png"];
    
    // POUR LES TESTS
    [[Level sharedLevel] initLevel:0 :5 :20 :100 :5 :1 :0.05 :11 :1 :1: 1: @"backgroundLevel1.png": @"imageLevel1.png"];
    
    self.view.backgroundColor = [[Level sharedLevel] colorBackground];
    [[[Level sharedLevel] colorBackground] release];
    
    
    progressViewLife.progress = [[Level sharedLevel] floatLifeProgress];
    
    [self initLabel]; // init des labels
    [self timerImage]; // deplacement image
    [self timerLevel:[[Level sharedLevel] intTimeLevel]]; // temps du niveau
    
    boolImageNotTouched = YES;
}

/* methode quand la partie est finie */
- (void)endGame {
    [self stopTimer];
    [self stopTimerLevel];
    
    endGameViewController = [[EndGameViewController alloc] initWithNibName:@"EndGameViewController" bundle:nil];
    endGameViewController.delegate = self;
    
    // pour initialiser les différents label de la vue end game
    endGameViewController .floatScoreLabel = [[Level sharedLevel] floatScore];
    endGameViewController .intCurrentLevel = [[Level sharedLevel] intCurrentLevel];
    
    endGameViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:endGameViewController animated:YES];
    [endGameViewController release];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        
    }
    return self;
}

- (void)dealloc
{
    [buttonPause release];
    
    for (UIButton *button in allButtons) {
        [button release];
    }
    
    for (UIImageView *imageview in allImagesView) {
        [imageview release];
    }
    
    [allImagesView release];
    [allButtons release];
    
    [labelScore release];
    
    [labelLife release];
    
    [progressViewLife release];
    [labelTime release];
    [labelLevel release];
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)initLabel {
    labelLevel.text = [NSString stringWithFormat:@"%d", [[Level sharedLevel] intCurrentLevel]];
    labelLife.text = [NSString stringWithFormat:@"%.0f", [[Level sharedLevel] floatLife]];
    labelScore.text = [NSString stringWithFormat:@"%.0f", [[Level sharedLevel] floatScore]];
    labelTime.text = [NSString stringWithFormat:@"%d", [[Level sharedLevel] intTimeLevel]];
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    allImagesView = [[NSArray alloc] initWithObjects:imageView11, imageView12, imageView13, imageView14, imageView15, imageView16, imageView17, imageView18, imageView21, imageView22, imageView23, imageView24, imageView25, imageView26, imageView27, imageView28,imageView31,imageView32,imageView33, imageView34, imageView35, imageView36, imageView37, imageView38, imageView41, imageView42, imageView43, imageView44, imageView45, imageView46, imageView47, imageView48, nil];
    
    allButtons = [[NSArray alloc] initWithObjects:button11, button12, button13, button14, button15, button16, button17, button18,button21, button22, button23,button24,button25,button26,button27,button28,button31,button32,button33,button34,button35,button36,button37,button38,button41,button42,button43,button44,button45,button46,button47,button48, nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(timerImage) name:@"TimerNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(restartGame) name:@"RestartNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(timerLevelBackToGame) name:@"TimerLevelBackToGameNotification" object:nil];
        
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addScoreNextExtra) name:@"AddScoreNextExtraNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(timerLevel:) name:@"TimerLevelNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initLabel) name:@"InitLabelNotification" object:nil];
    [self randomPositionImage];    
    [self restartGame];

}

- (void)viewDidUnload
{
    
    for (UIButton *buttons in allButtons) {
        buttons = nil;
    }
    
    for (UIImageView *imageview in allImagesView) {
        imageview = nil;
    }
    
    [self setButtonPause:nil];
    [self setLabelScore:nil];
    
    self.allButtons = nil;
    self.allImagesView = nil;
    
    [self setLabelLife:nil];
    [self setProgressViewLife:nil];
    [self setLabelTime:nil];
    [self setLabelLevel:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

@end
